package hnlg.com.cn.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import hnlg.com.cn.service.MyUserDetailService;


@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
   
	@Autowired
	MyUserDetailService userService;
	
	 @Bean
	  PasswordEncoder passwordEncoder() {
	    return new BCryptPasswordEncoder();
	  }
	 
	@Override
	protected void configure(AuthenticationManagerBuilder auth)throws Exception{
		//解决Bcrypt加密与数据库格式不匹配问题，加上password encoder
		auth.userDetailsService(userService);
	}
	
	  @Bean
	  //设置权限继承
	  RoleHierarchy roleHierarchy() {
	    RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
	    String hierarchy = " ROLE_ADMIN > ROLE_USER";
	    roleHierarchy.setHierarchy(hierarchy);
	    return roleHierarchy;
	  }
	
	@Override
	protected void configure(HttpSecurity http)throws Exception{
		//定制请求的授权规则
		http.formLogin().permitAll()
		.and()
		.authorizeRequests()
		.antMatchers("/login").permitAll()//保护的url，需要用户登录
		.antMatchers("/HetongControl/**").hasRole("USER")
		.antMatchers("/LocationControl/**").hasRole("ADMIN")
		.antMatchers("/UnitControl/**").hasRole("ADMIN")
		.anyRequest().authenticated()
		.and()
		//开启自动配置的登录功能:/login来到登录页,登录错误会重定向到login?error
	    
	    //.usernameParameter("name").passwordParameter("password")
	    //.loginPage("/userLogin")
	    //必须允许所有的用户访问我们的登录页,例如未验证的用户，否则验证流程就会进入死循环
	    .csrf()
	    .disable();	
		
		//访问/logout 表示用户注销，并清空session,注销成功后会来到/login?logout页面，
		//可定制访问成功后返回页面
		http.logout().logoutSuccessUrl("/login");
		//开启记住我功能，security登录后会给浏览器发送一个cookie，存储用户信息，注销后会删除
		http.rememberMe();
	}
	
}
